<script setup lang="ts" name="VideoForm">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { FileApi, FileVideoType } from '@/api/infra/resource/library'
import { getAcceptSize } from '@/utils/file/helper'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const visible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  name: '',
  description: '',
  coverImageId: undefined,
  url: '',
  coverImage: undefined as unknown as FileVideoType,
  width: 0,
  height: 0
})
const formRules = reactive({
  name: [{ required: true, message: t('infra.resource.library.file.edit.media.rules', 'name'), trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const videoRef = ref() // 视频 ref
const previewImageList = ref<string[]>([]) // 预览图
const isPreview = ref(false) // 预览状态
const acceptSize = ref() // 提示文本

/** 打开弹窗 */
const open = async (id: number) => {
  visible.value = true
  resetForm()
  // 设置数据
  formLoading.value = true
  try {
    formData.value = await FileApi.detail(id)
    if (formData.value.coverImageId) {
      previewImageList.value = [formData.value.coverImage.url]
    } else {
      formData.value.coverImage = {
        url: ''
      }
    }
    acceptSize.value = await getAcceptSize('image')
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const resBody = new FormData()
    resBody.append('name', formData.value.name as string)
    if (formData.value && formData.value.id) {
      resBody.append('id', formData.value.id + '')
    }
    resBody.append('description', formData.value.description as string)
    if (formData.value && formData.value.coverImageId) {
      resBody.append('coverImageId', formData.value.coverImageId + '')
    }
    await FileApi.update(resBody)
    message.success(t('message', 'updateSuccess'))
    visible.value = false
    // 发送操作成功的事件
    emit('success', true)
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    description: '',
    coverImageId: undefined,
    url: '',
    coverImage: undefined as unknown as FileVideoType,
    width: 0,
    height: 0
  }
  previewImageList.value = []
  isPreview.value = false
  formRef.value?.resetFields()
}

// 选择资源弹窗确定后，返回已选择的资源
const handleResourcePickerChange = (v) => {
  if (v) {
    formData.value.coverImage = v
    formData.value.coverImageId = v.id
    previewImageList.value.push(v.url)
  } else {
    formData.value.coverImage = {
      url: ''
    }
    formData.value.coverImageId = undefined
    previewImageList.value = []
  }
}
</script>

<template>
  <Dialog v-model="visible" :title="t('infra.resource.library.file.edit.media', 'title')" width="960px">
    <div v-loading="formLoading && systemConfig.loadingType === 'module'" class="video-edit-wrap">
      <div class="video-edit-left">
        <div class="video-edit-content">
          <div class="el-video">
            <video ref="videoRef" :src="formData.url" autoplay loop controls />
          </div>
        </div>
      </div>
      <div class="video-edit-right">
        <ElForm ref="formRef" label-width="auto" label-position="top" :model="formData" :rules="formRules">
          <ElFormItem :label="t('infra.resource.library.file.edit.media', 'name')" prop="name">
            <ElInput v-model="formData.name" clearable maxlength="50" show-word-limit placeholder="" />
          </ElFormItem>
          <ElFormItem :label="t('infra.resource.library.file.edit.media', 'description')">
            <ElInput v-model="formData.description" type="textarea" clearable maxlength="150" :autosize="false" resize="none" show-word-limit placeholder="" />
          </ElFormItem>
          <ElFormItem v-if="formData.coverImage" :label="t('infra.resource.library.file.edit.media', 'coverImage')">
            <UploadImage v-model="formData.coverImage.url" mimetype="image" size="126px" type="picker" :limit="1" :width="formData.width" :height="formData.height" @success="handleResourcePickerChange" />
          </ElFormItem>
        </ElForm>
      </div>
    </div>
    <template #footer>
      <el-button @click="visible = false">{{ t('action', 'cancel') }}</el-button>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">{{ t('action', 'confirm') }}</el-button>
    </template>
  </Dialog>
</template>

<style scoped lang="scss">
.video-edit-wrap {
  display: flex;
  flex-direction: row;

  .video-edit-left,
  .video-edit-right {
    height: 360px;
  }

  .video-edit-left {
    width: 50%;
  }

  .video-edit-right {
    width: 50%;
    padding-left: var(--el-space);

    .el-form {
      overflow: hidden;

      .el-form-item {
        :deep(.el-form-item__content) {
          .el-textarea {
            .el-textarea__inner {
              height: 88px;
            }
          }
        }
      }
    }
  }

  .video-edit-content {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 360px;
    overflow: hidden;
    background: #000;

    .el-video {
      max-width: 100%;
      max-height: 100%;
      overflow: hidden;

      video {
        width: 100%;
        height: 100%;
        max-width: 100%;
        max-height: 360px;
        object-fit: fill;
      }
    }
  }

  .video-edit-group {
    display: flex;
    padding-top: 20px;
    margin-top: 20px;
    border-top: 1px solid var(--el-border-color-lighter);
    align-items: center;
    justify-content: space-around;
  }
}

.video-image {
  display: flex;
  flex: 1;
  padding: 6px;

  .image-preview {
    position: relative;
    display: flex;
    width: 126px;
    height: 126px;
    overflow: hidden;
    background-color: var(--el-fill-color-lighter);
    border: 1px solid var(--el-border-color-darker);
    border-radius: 6px;
    box-sizing: border-box;
    align-items: center;
    justify-content: center;

    &:hover {
      .mask {
        opacity: 1;
        visibility: visible;
      }
    }

    .mask {
      position: absolute;
      top: 0;
      left: 0;
      z-index: 10;
      display: flex;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      opacity: 0;
      visibility: hidden;
      transition: all 0.3s;
      align-items: center;
      justify-content: center;

      .el-icon {
        margin: 0 6px;
        font-size: 24px !important;
        color: #fff;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          font-size: 32px !important;
        }
      }
    }

    .el-image {
      max-width: 124px;
      max-height: 124px;
    }
  }

  .upload-image {
    display: flex;
    width: 126px;
    height: 126px;
    cursor: pointer;
    background-color: var(--el-fill-color-lighter);
    border: 1px dashed var(--el-border-color-darker);
    border-radius: 6px;
    box-sizing: border-box;
    align-items: center;
    justify-content: center;

    &:hover {
      border-color: var(--el-color-primary);
    }
  }

  .video-tips {
    display: flex;
    flex: 1;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-end;
    padding-left: 10px;

    p {
      margin: 0;
      font-size: 12px;
      line-height: 24px;
      color: var(--el-text-color-secondary);
    }

    .tips {
      :deep(.el-text){
        display: flex;

        span{
          margin: 0 6px;
          color: var(--el-color-primary);
        }
      }
    }
  }
}
</style>
